import IconApp from '@/components/icon/IconApp';
import IconBiliBili from '@/components/icon/IconBiliBili';
import IconDouyin from '@/components/icon/IconDouyin';
import IconKuaishou from '@/components/icon/IconKuaishou';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeb from '@/components/icon/IconWeb';
import IconWeChatChannels from '@/components/icon/IconWeChatChannels';
import IconWeChatOfficialAccount from '@/components/icon/IconWeChatOfficialAccount';
import IconWeibo from '@/components/icon/IconWeibo';
import { listAuditSource, pageMonitorhcRecord } from '@/services/api/api-monitorhc';
import { pageMonitorVideoRecordStatistics } from '@/services/api/api-monitorhc-video';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import type { ActionType, FormInstance, ProColumns } from '@ant-design/pro-components';
import {
  PageContainer,
  ProForm,
  ProFormDateRangePicker,
  ProFormRadio,
  ProFormSelect,
  ProTable,
  QueryFilter,
} from '@ant-design/pro-components';
import { Button, Descriptions, Flex, Space, Tag } from 'antd';
import moment from 'moment';
import RcResizeObserver from 'rc-resize-observer';
import { useEffect, useRef, useState } from 'react';
import DetailsMonitorArticle from '../../article/components/DetailMonitorArticle';
import DetailMonitorVideo from '../../video/components/DetailMonitorVideo';
import AddMonitorDisposeReply from '../components/AddMonitorDisposeReply';
import DetailMonitorDisposeContent from '../components/DetailMonitorDisposeContent';
interface PageMonitorDisposeProps { }

const PageMonitorDispose: React.FC<PageMonitorDisposeProps> = (props) => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [width, setWidth] = useState(500);
  const [cascadersSourceData, setCascadersSourceDataState] = useState<
    MonitorData.CascadersSource[]
  >([]);

  const [pageMonitorVideoRecordStatisticsData, setPageMonitorVideoRecordStatisticsDataState] =
    useState<MonitorVideoData.VideoRecordPageStatistics[]>([]);

  const [optionsCascadersSourceData, setOptionsCascadersSourceDataState] = useState<
    { label: string; value: string; datahubChannelId: string }[]
  >([]);
  const [listAuditSourceData, setListAuditSourceDataState] = useState<
    { label: string; value: string; datahubChannelId: string }[]
  >([]);

  const loadListAuditSource = async () => {
    const res = await listAuditSource();
    if (res.code === 0) {
      console.log(res.data);
      const option =
        Array.isArray(res.data) &&
        res.data.map((item) => {
          return {
            label: (
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <div>{item.datahubSourceName}</div>
                <div style={{ color: '#1677FF' }}>{item.datahubChannelName}</div>
              </div>
            ),
            value: item.datahubSourceId,
            datahubChannelId: item.datahubChannelId,
          };
        });
      setOptionsCascadersSourceDataState(option);
      setListAuditSourceDataState(option);
    }
  };

  useEffect(() => {
    loadListAuditSource();
  }, []);
  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({
    datahubChannelIds: [
      '8117112411979845',
      '8117112410996805',
      '8117112412962885',
      '8117112414076995',
      '8117112419123365',
      '8117112412962886',
      '8117112414994505',
    ],
  });

  const handleResolve = async (id: string) => {
    // const res = await monitorLinkageUpdate({ id });
    // console.log(res);
  };

  const columns: ProColumns<MonitorhcData.RecordPage>[] = [
    {
      title: '处置状态',
      width: 120,
      dataIndex: 'disposeState',
      align: 'center',
      render: (dom, row) => (
        <>
          <Tag
            icon={
              row?.disposeState == 1 ? (
                <QuestionCircleOutlined />
              ) : row?.disposeState == 2 ? (
                <ExclamationCircleOutlined />
              ) : (
                <CheckCircleOutlined />
              )
            }
            color={
              row?.disposeState == 1 ? 'processing' : row?.disposeState == 2 ? '#f50' : 'success'
            }
          >
            {row?.disposeState == 1 ? '无需处置' : row?.disposeState == 2 ? '需要处置' : '处置完成'}
          </Tag>
        </>
      ),
    },
    {
      title: '状态',
      width: 80,
      align: 'center',
      render: (dom, row) => (
        <>
          {(row.violationLevel == undefined || row.violationLevel == 0) ? (
            <Tag icon={<CheckCircleOutlined />} color={'success'}>
              正常
            </Tag>
          ) : row.violationLevel == 1 ? (
            <Tag icon={<InfoCircleOutlined />} color={'warning'}>
              {'警告'}
            </Tag>
          ) : row.violationLevel == 2 ? (
            <Tag icon={<InfoCircleOutlined />} color={'warning'}>
              {'问题'}
            </Tag>
          ) : (
            <Tag icon={<CloseCircleOutlined />} color={'error'}>
              {'告警'}
            </Tag>
          )}
        </>
      ),
    },
    {
      title: '标题',
      dataIndex: 'dataName',
      hideInSearch: true,
      ellipsis: true,
      align: 'center',
      render: (dom, row) => (
        // <DetailMonitorLinkage
        //     data={row}
        //     onRefurbish={() => {
        //         actionRef.current?.reload()
        //     }}
        // />
        <>
          {row.greenTypes[0] === 'text' ? (
            <DetailsMonitorArticle
              record={row}
              onRefurbish={function (): void {
                actionRef.current?.reload();
              }}
            />
          ) : (
            <DetailMonitorVideo
              record={row}
              onRefurbish={() => {
                actionRef.current?.reload();
              }}
            />
          )}
        </>
      ),
    },

    {
      title: '账号',
      key: 'datahubSourceName',
      dataIndex: 'datahubSourceName',
      align: 'center',
      render: (dom, entity, index, action) => {
        const datahubChannelName = entity.datahubChannelName;
        let icon;
        if (datahubChannelName == '微信公众号') {
          icon = <IconWeChatOfficialAccount width={15} height={15} />;
        } else if (datahubChannelName == '微信视频号') {
          icon = <IconWeChatChannels width={15} height={15} />;
        } else if (datahubChannelName == '微博') {
          icon = <IconWeibo width={15} height={15} />;
        } else if (datahubChannelName == '抖音') {
          icon = <IconDouyin width={15} height={15} />;
        } else if (datahubChannelName == '今日头条') {
          icon = <IconToutiao width={15} height={15} />;
        } else if (datahubChannelName == '快手') {
          icon = <IconKuaishou width={15} height={15} />;
        } else if (datahubChannelName == '哔哩哔哩') {
          icon = <IconBiliBili width={15} height={15} />;
        } else if (datahubChannelName == '客户端') {
          icon = <IconApp width={15} height={15} />;
        } else if (datahubChannelName == '网站') {
          icon = <IconWeb width={15} height={15} />;
        }

        return (
          <Flex justify={'center'} align={'center'}>
            <>{icon}</>
            <>{entity.datahubSourceName}</>
          </Flex>
        );
      },
    },

    {
      title: '单位',
      key: 'auditSourceResponsibleOrganizationNames',
      dataIndex: 'auditSourceResponsibleOrganizationNames',
      align: 'center',

      render: (dom, row) => (
        <>
          <Space>{row.auditSourceResponsibles.map((item) => item.responsibleOrganizationName).join('/')}</Space>
        </>
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'dataReleaseTime',
      key: 'dataReleaseTime',
      width: '180px',
      align: 'center',
      search: false,
    },
    // {
    //   title: '问题',
    //   key: 'violationCause',
    //   dataIndex: 'violationCause',
    //   hidden: true,
    //   align: 'center',
    //   render: (dom, row) => (
    //     <>
    //       <Space wrap>
    //         {row.violationCause?.map((item) => (
    //           <Tag color="error">{item}</Tag>
    //         ))}
    //       </Space>
    //     </>
    //   ),
    // },
    {
      title: '操作',
      dataIndex: 'articleUrl',
      key: 'articleUrl',
      width: '120px',
      align: 'center',
      search: false,
      render: (dom, entity, index, action, schema) => {
        if (entity.disposeState == 1) {
          return <></>;
        } else if (entity.disposeState == 2) {
          return (
            <AddMonitorDisposeReply
              data={entity}
              onRefurbish={() => {
                actionRef.current?.reload();
              }}
            />
          );
        } else if (entity.disposeState == 3) {
          return <DetailMonitorDisposeContent data={entity} onRefurbish={function (): void { }} />;
        }
      },
    },
  ];

  const loadPageMonitorVideoRecordStatistics = async (queryParam: any) => {
    const response = await pageMonitorVideoRecordStatistics(queryParam);
    if (response.code == 0) {
      setPageMonitorVideoRecordStatisticsDataState(response.data);
    }
  };

  return (
    <PageContainer
      style={{ background: '#FFF' }}
      header={{
        breadcrumb: {
          items: [],
        },
        style: {
          paddingBlockEnd: 0,
        },
      }}
      content={
        <RcResizeObserver
          key="resize-observer"
          onResize={(size) => {
            setWidth(size.width);
          }}
        >
          <QueryFilter
            submitter={false}
            span={24}
            labelWidth="auto"
            split
            formRef={formRef}
            initialValues={{
              datahubChannel: '全部', //渠道=全部
              // time: '最近90天',
              // releaseTimes: [moment().subtract(89, 'days'), moment()],
            }}
            onFinish={async (value) => {
              const datahubChannelIds = [];
              const datahubSourceIds = [];
              console.log(value.datahubChannel);

              if (value.datahubChannel) {
                if (value.datahubChannel === '全部') {
                  datahubChannelIds.push(
                    ...[
                      '8117112411979845',
                      '8117112410996805',
                      '8117112412962885',
                      '8117112414076995',
                      '8117112419123365',
                      '8117112412962886',
                      '8117112414994505',
                    ],
                  );
                } else {
                  datahubChannelIds.push(value.datahubChannel);
                }
              }
              if (value.datahubChannelId) {
                datahubSourceIds.push(value.datahubChannelId);
              }
              if (value.releaseTimes) {
                value.startTime = value.releaseTimes[0];
                value.endTime = value.releaseTimes[1];
              }
              value.datahubChannelIds = datahubChannelIds;
              value.datahubSourceIds = datahubSourceIds;
              setQueryParamState({ ...queryParam, ...value });
              actionRef.current?.reloadAndRest();
            }}
          >
            <ProForm.Group title="平台">
              <ProFormRadio.Group
                name="datahubChannel"
                radioType="button"
                // options={optionsPlatformData}
                options={[
                  { label: '全部', value: '全部' },
                  { label: '客户端', value: '8117112411979845' },
                  {
                    label: '网站',
                    value: '8117112410996805',
                  },
                  {
                    label: '微信公众号',
                    value: '8117112412962885',
                  },
                  {
                    label: '微博',
                    value: '8117112414076995',
                  },
                  {
                    label: '今日头条',
                    value: '8117112419123365',
                  },
                  { label: '微信视频号', value: '8117112412962886' },
                  {
                    label: '抖音',
                    value: '8117112414994505',
                  },
                ]}
                fieldProps={{
                  buttonStyle: 'solid',
                  onChange: (value) => {
                    formRef.current?.setFieldValue('datahubChannelId', null);
                    if (value.target.value === '全部') {
                      setOptionsCascadersSourceDataState(listAuditSourceData);
                    } else {
                      setOptionsCascadersSourceDataState(
                        listAuditSourceData.filter(
                          (item) => item.datahubChannelId === value.target.value,
                        ),
                      );
                    }
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormSelect
                options={optionsCascadersSourceData}
                name="datahubChannelId"
                fieldProps={{
                  options: optionsCascadersSourceData,
                  style: {
                    width: (width / 3) * 0.95,
                  },
                  removeIcon: true,
                  allowClear: true,
                  showSearch: true,
                  maxTagCount: 'responsive',
                  onClear() {
                    setTimeout(() => {
                      formRef.current?.setFieldValue('datahubChannel', '全部');
                      formRef.current?.submit();
                    }, 0);
                  },
                  onChange(value, selectOptions) {
                    formRef.current?.setFieldValue('datahubChannel', null);
                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>
            <ProForm.Group title="发布时间">
              <ProFormRadio.Group
                name="time"
                radioType="button"
                options={[
                  { label: '今天', value: '今天' },
                  { label: '本月', value: '本月' },
                  { label: '上月', value: '上月' },
                  { label: '最近7天', value: '最近7天' },
                  { label: '最近60天', value: '最近60天' },
                  { label: '最近90天', value: '最近90天' },
                ]}
                fieldProps={{
                  buttonStyle: 'solid',
                  onChange: () => {
                    const time = formRef.current?.getFieldValue('time');
                    if (time === '今天') {
                      formRef.current?.setFieldValue('releaseTimes', [moment(), moment()]);
                    } else if (time === '本月') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().startOf('month'),
                        moment().endOf('month'),
                      ]);
                    } else if (time === '上月') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().startOf('month').subtract(1, 'months'),
                        moment().endOf('month').subtract(1, 'months'),
                      ]);
                    } else if (time === '最近7天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(6, 'days'),
                        moment(),
                      ]);
                    } else if (time === '最近60天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(59, 'days'),
                        moment(),
                      ]);
                    } else if (time === '最近90天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(89, 'days'),
                        moment(),
                      ]);
                    }
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormDateRangePicker
                name="releaseTimes"
                fieldProps={{
                  onChange(dates, dateStrings) {
                    formRef.current?.setFieldValue('time', ' ');
                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>
          </QueryFilter>
        </RcResizeObserver>
      }
    >
      <ProTable<MonitorhcData.RecordPage>
        cardBordered
        actionRef={actionRef}
        columns={columns}
        request={async (params = {}) => {
          const response = await pageMonitorhcRecord({
            isViolation: 1,
            ...params,
            ...queryParam,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        search={false}
        rowKey="key"
        options={false}
        toolBarRender={() => [
          <>
            <div
              style={{
                marginLeft: 10,
              }}
            >
              <Button
                onClick={() => {
                  actionRef.current?.reload();
                }}
                type="primary"
              >
                刷新
              </Button>
            </div>
          </>,
        ]}
        toolbar={{
          search: {
            placeholder: '请输入文章标题搜索',
            allowClear: true,
            onSearch: (value: string) => {
              setQueryParamState({ ...queryParam, content: value });
              formRef.current?.submit();
            },
          },
        }}
        headerTitle={
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
            }}
          >
            {pageMonitorVideoRecordStatisticsData &&
              pageMonitorVideoRecordStatisticsData.length > 0 && (
                <Descriptions
                  size="small"
                  layout="vertical"
                  bordered
                  column={
                    pageMonitorVideoRecordStatisticsData &&
                    pageMonitorVideoRecordStatisticsData.length
                  }
                  labelStyle={{ color: '#CF1322' }}
                  className="description"
                >
                  {pageMonitorVideoRecordStatisticsData.map((item) => (
                    <Descriptions.Item label={item.label} style={{ textAlign: 'center' }}>
                      <span style={{ color: '#FF4D4F' }}>{item.value}</span>
                    </Descriptions.Item>
                  ))}
                </Descriptions>
              )}
          </div>
        }
      />
    </PageContainer>
  );
};

export default PageMonitorDispose;
